import { defineStore } from "pinia";
import { ref } from "vue";
import { invoke } from "@tauri-apps/api/core";

export type ThemeMode = "system" | "light" | "dark";

export interface Settings {
  theme: ThemeMode;
  opacity: number;
  viewMode?: "list" | "calendar";
  floatingWindowBounds?: {
    x: number;
    y: number;
    width: number;
    height: number;
  };
}

export const useSettingsStore = defineStore("settings", () => {
  const settings = ref<Settings>({
    theme: "system",
    opacity: 0.95,
    viewMode: "list",
  });

  // 加载设置
  async function loadSettings() {
    try {
      const data = await invoke<string>("load_settings");
      settings.value = JSON.parse(data);
    } catch (error) {
      console.error("Failed to load settings:", error);
    }
  }

  // 保存设置
  async function saveSettings() {
    try {
      await invoke("save_settings", { data: JSON.stringify(settings.value) });
    } catch (error) {
      console.error("Failed to save settings:", error);
    }
  }

  // 设置主题
  function setTheme(theme: ThemeMode) {
    settings.value.theme = theme;
    saveSettings();
  }

  // 设置透明度
  function setOpacity(opacity: number) {
    settings.value.opacity = opacity;
    saveSettings();
  }

  // 保存窗口位置和尺寸
  function saveWindowBounds(bounds: Settings["floatingWindowBounds"]) {
    settings.value.floatingWindowBounds = bounds;
    saveSettings();
  }

  // 切换视图模式
  function toggleViewMode() {
    settings.value.viewMode =
      settings.value.viewMode === "list" ? "calendar" : "list";
    saveSettings();
  }

  return {
    settings,
    loadSettings,
    saveSettings,
    setTheme,
    setOpacity,
    saveWindowBounds,
    toggleViewMode,
  };
});
